package com.kuang.service;

import com.kuang.config.RedisConfig;
import com.kuang.mapper.UserMapper;
import com.kuang.springcloud.pojo.Userinfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class UserServiceImpl implements UserService{
/**
 * @description：TODO

 * @author     ：LK
 * @date       ：Created in 2021-10-26 15:08
 */

@Autowired
private UserMapper userMapper;
@Autowired
private RedisTemplate redisTemplate;

    @Override
    public List<Userinfo> findAll() {
        return userMapper.findAll();
    }

    @Override
    public Userinfo getuserByUsername(String username) {
        return userMapper.getuserByUsername(username);
    }

    @Override
    public int updateWhole(Userinfo user) {
        return userMapper.updateWhole(user);
    }

    @Override
    public int adduser(Userinfo user) {
        return userMapper.adduser(user);
    }

//    以下是为测试redis的缓存的
    /**
     * 获取用户策略:先从缓存中获取用户，没有则读mysql数据，再将数据写入缓存
     */
    @Override
    public Userinfo getuserByUsernameRedis(String username) {
        ValueOperations<String,Userinfo> valueOperations = redisTemplate.opsForValue();
        Boolean hasKey = redisTemplate.hasKey(username);
        //判断redis中是否有键为key的缓存
        if (hasKey){
            Userinfo user = valueOperations.get(username);
            System.out.println("从缓存中获取数据:"+user.getUsername());
            System.out.println("-----------------------------");
            return user;
        }else {
            Userinfo user = userMapper.getuserByUsername(username);
            System.out.println("查询数据库获取数据:"+user.getUsername());
            //写入缓存
            valueOperations.set(username,user,5, TimeUnit.HOURS);
            return user;
        }
    }

    /**
     * 删除用户策略:删除数据表中数据，然后删除缓存
     */

/**
 * 更新用户策略：先更新数据表，成功之后，删除原来的缓存，再更新缓存
 */


 //    以下为测试redis 的操作

}
